﻿CREATE PROCEDURE [dbo].[utl_CreateSPForAllTables]
@ParentObject [sysname]=NULL
AS
BEGIN
	DECLARE @ID    INT
	DECLARE @Table sysname
	
	DECLARE @Tables TABLE (
				ID INTEGER IDENTITY(1, 1) PRIMARY KEY, 
				TableName sysname
			)
	
	INSERT INTO @Tables
	  (
	    TableName
	  )
	SELECT TableName
	FROM   dbo.fn_Tables()
	
	IF @ParentObject IS NULL
	BEGIN
	    EXECUTE [dbo].[utl_CreateSPScriptTable]
	    SET @ParentObject = OBJECT_NAME(@@PROCID)
	END
	
	SELECT @ID = MIN(ID)
	FROM   @Tables
	
	WHILE @ID IS NOT NULL
	BEGIN
	    SELECT @Table = TableName
	    FROM   @Tables
	    WHERE  ID = @ID
	    
	    EXECUTE [dbo].[utl_CreateSPForTable] @Table, @ParentObject
	    
	    SELECT @ID = MIN(ID)
	    FROM   @Tables
	    WHERE  ID > @ID
	END
	
	IF @ParentObject IS NULL
	BEGIN
	    SELECT Line
	    FROM   CreateSPScriptTable
	    ORDER BY
	           ID
	END
/*	    
	    DECLARE @cmd  NVARCHAR(MAX)
	    DECLARE @db   sysname
	    SET @cmd = 'SELECT LINE FROM CreateSPScriptTable'
	    SET @db = DB_NAME()
	    EXECUTE MASTER..xp_execresultset @cmd, @db
*/
END

